import request from "../../../utils/request";

// pages/music-player/music-player.js
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    songs: [],
    randomSongs: [],
    currentSongIndex: 0,
    // 当前正在播放歌曲
    song: {},

    startTime: 0,
    endTime: 0,
    startTimeText: '00:00',
    endTimeText: '00:00',

    lineWidth: 0,
    pointScaleClass: '',
    isSkiping: false,

    isPlaying: true,
    animationRotate: '',
    rotate: 0,

    visible: false,

    /*
      1 列表循环 icon-repeat
      2 随机播放 icon-shuffle
      3 单曲循环 icon-repeatOnce
    */
    playMode: 1,
    playModeClass: 'icon-repeat',
    songUrl: '',

    lyric: [],
    currentLyricIndex: 0,
    isLyricSkiping: false,
    isLyricShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const songs = app.globalData.songs;
    this.setData({
      songs,
      randomSongs: [...songs].sort(() => Math.random() - 0.5),
      currentSongIndex: app.globalData.currentSongIndex,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    
    this._playSong();

    // 获取进度条的总宽度
    wx.createSelectorQuery().select('.music-line-wrap').boundingClientRect().exec((res) => {
      // console.log(res);
      this.totalLineWidth = res[0].width;
      this.totalLineLeft = res[0].left;
    })
   
    const animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear',
    })

    // 监听背景音频播放进度更新事件
    this.backgroundAudioManager.onTimeUpdate(() => {

      const rotate = this.data.rotate + 3;
      animation.rotate(rotate).step();
      this.setData({
        animationRotate: animation.export(),
        rotate
      })

      if (this.data.isSkiping) return
      // backgroundAudioManager.currentTime 当前音乐播放的实时时间
      const startTime = this.backgroundAudioManager.currentTime * 1000;

      

      // 进度条的宽度
      const lineWidth = startTime / this.data.endTime * 100 + '%';

      this.setData({
        startTime: startTime,
        startTimeText: this._formatTime(startTime),
        lineWidth,
      })

      if (this.data.isLyricSkiping) return;

      let index = this.data.lyric.findIndex(item => item.time > startTime);
      index--;
      if (!this.data.lyric[index].text) {
        index--;
      }

      this.setData({
        currentLyricIndex: index
      })

    })
    // 监听背景音频自然播放结束事件
    this.backgroundAudioManager.onEnded(() => {
      if (this.data.playMode === 3) {
        // 单曲循环
        this.backgroundAudioManager.src = this.data.songUrl;
        this.backgroundAudioManager.title = this.data.song.name;
        return;
      }
      // 列表循环和随机播放
      this.nextSong();
    })
  },

  _formatTime(time) {
    const date = new Date(time);
    let m = date.getMinutes();
    let s = date.getSeconds();
    // 补0
    m = m >= 10 ? m : '0' + m;
    s = s >= 10 ? s : '0' + s;

    return `${m}:${s}`
  },

  // 跳转进度
  skipProcess(e) {
    /*
      公式：
        （当前点距离左侧距离 - 总线距离左侧距离）/ 总线长 * 总时间
    */
    // 单位ms
    const time = (e.detail.x - this.totalLineLeft) / this.totalLineWidth * this.data.endTime;

    // 单位s
    this.backgroundAudioManager.seek(time / 1000);
  },

  // 小圆点拖拽
  handleSkipStart() {
    this.setData({
      // 小圆点缩放
      pointScaleClass: 'point-scale',
      // 用于在onUpdateTime事件中阻止更新小圆点位置
      isSkiping: true
    })
  },
  handleSkipMove(e) {
    let precent = (e.changedTouches[0].pageX - this.totalLineLeft) / this.totalLineWidth;
    // 边界值判断
    if (precent < 0) {
      precent = 0
    } else if (precent > 1) {
      precent = 1
    }

    const lineWidth =  precent * 100 + '%';
    const startTime = precent * this.data.endTime;
    this.setData({
      lineWidth,
      startTime,
      startTimeText: this._formatTime(startTime)
    })
  },
  handleSkipEnd() {
    this.setData({
      pointScaleClass: '',
      isSkiping: false
    });
    // 跳转进度
    this.backgroundAudioManager.seek(this.data.startTime / 1000);
  },

  // 切换播放暂停
  switchPlay() {
    const isPlaying = !this.data.isPlaying;

    if (isPlaying) {
      this.backgroundAudioManager.play();
    } else {
      this.backgroundAudioManager.pause();
    }

    this.setData({
      isPlaying
    })
  },

  async _playSong() {

    // 获取全局唯一的背景音频管理器
    let backgroundAudioManager = this.backgroundAudioManager;
    if (!backgroundAudioManager) {
      backgroundAudioManager = wx.getBackgroundAudioManager();
      this.backgroundAudioManager = backgroundAudioManager;
    }

    const { playMode } = this.data
    
    const song = this.data[playMode === 2 ? 'randomSongs' : 'songs'][this.data.currentSongIndex];

    this.setData({
      song
    })

    // 请求音乐url
    const res = await request('/song/url/v1', {
      id: song.id,
      level: 'standard'
    });

    const {
      url,
      time
    } = res.data[0];

    // 音频的数据源
    // 当设置了新的 src 时，会自动开始播放
    backgroundAudioManager.src = url;
    // 音频标题
    backgroundAudioManager.title = song.name;

    this.setData({
      startTime: 0,
      endTime: time,
      startTimeText: '00:00',
      endTimeText: this._formatTime(time),
      songUrl: url
    })

    // 请求歌词
    const lyricRes = await request('/lyric', { id: song.id });

    this.setData({
      lyric: this._formatLyric(lyricRes.lrc.lyric)
    })
  },

  _formatLyric(orginLyric) {
    const lyric = [];
    const arr = orginLyric.split("\n").filter(Boolean);
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      let [time, text] = item.split("]");
      text = text.trim();
      let [m, s] = time.split(":");
      m = m.replace("[", "");
      lyric.push({
        id: i + 1,
        text,
        time: m * 60000 + s * 1000,
      });
    }
    return lyric;
  },

  // 上一首
  previousSong() {
    const { songs } = this.data
    // 1. 获取到下标，-1
    let currentSongIndex = this.data.currentSongIndex - 1;
    if (currentSongIndex < 0) {
      currentSongIndex = songs.length - 1;
    }
    this.setData({
      currentSongIndex
    })
    // 2. 通过最新下标获取歌曲数据
    // 3. 通过歌曲id请求歌曲url
    // 4. 设置backgroundAudioManager.src, 自动播放新歌曲
    this._playSong()
  },
  // 下一首
  nextSong() {
    const { songs } = this.data
    // 1. 获取到下标，-1
    let currentSongIndex = this.data.currentSongIndex + 1;
    if (currentSongIndex > songs.length - 1) {
      currentSongIndex = 0;
    }
    this.setData({
      currentSongIndex
    })
    // 2. 通过最新下标获取歌曲数据
    // 3. 通过歌曲id请求歌曲url
    // 4. 设置backgroundAudioManager.src, 自动播放新歌曲
    this._playSong()
  },

  // 显示播放列表
  showPlayerList() {
    this.setData({
      visible: true
    })
  },

  setVisible(e) {
    this.setData({
      visible: e.detail // 组件触发事件通信的数据
    })
  },

  setCurrentSongIndex(e) {
    app.globalData.currentSongIndex = e.detail;
    this.setData({
      currentSongIndex: e.detail // 组件触发事件通信的数据
    })
    this._playSong();
  },

  // 切换播放模式
  switchPlayMode() {
    let { playMode, playModeClass, currentSongIndex} = this.data;

    if (playMode === 1) {
      playMode = 2;
      playModeClass = 'icon-shuffle'
      currentSongIndex = this.data.randomSongs.findIndex(song => song.id === this.data.song.id);
    } else if (playMode === 2) {
      playMode = 3;
      playModeClass = 'icon-repeatOnce'
      currentSongIndex = this.data.songs.findIndex(song => song.id === this.data.song.id);
    } else {
      playMode = 1;
      playModeClass = 'icon-repeat'
    }
    this.setData({
      playMode,
      playModeClass,
      currentSongIndex
    })
  },

  handleLyricTouchStart() {
    this.setData({
      isLyricSkiping: true,
    })
  },
  handleLyricTouchEnd() {
    clearTimeout(this.timeId);
    this.timeId = setTimeout(() => {
      this.setData({
        isLyricSkiping: false,
      })
    }, 2000)
  },
  switchLyricShow() {
    this.setData({
      isLyricShow: !this.data.isLyricShow
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});